<template>
  <div class="profile-container container">
    <div class="page-title">
      <h2>个人资料</h2>
    </div>
    
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="8" :lg="6">
        <div class="user-card card">
          <div class="user-avatar">
            <el-avatar :size="100" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
            <el-button type="text" class="change-avatar">更换头像</el-button>
          </div>
          <div class="user-info">
            <h3 class="user-name">{{ userInfo.username }}</h3>
            <p class="user-id">会员ID: {{ userInfo.id }}</p>
            <p class="user-since">注册时间: {{ userInfo.createTime }}</p>
          </div>
          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-value">{{ userInfo.orderCount }}</div>
              <div class="stat-label">租车订单</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userInfo.favoriteCount }}</div>
              <div class="stat-label">收藏车辆</div>
            </div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="24" :md="16" :lg="18">
        <div class="info-card card">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="基本信息" name="basic">
              <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="100px">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="userForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="userForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userForm.email"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="userForm.realName"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="userForm.gender">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                    <el-radio :label="0">保密</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="生日" prop="birthday">
                  <el-date-picker type="date" placeholder="选择日期" v-model="userForm.birthday" style="width: 100%"></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateUserInfo" :loading="loading">保存修改</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <el-tab-pane label="证件信息" name="certificates">
              <el-form :model="certForm" :rules="certRules" ref="certForm" label-width="100px">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="certForm.idCard" placeholder="请输入身份证号码"></el-input>
                </el-form-item>
                <el-form-item label="驾驶证号" prop="driverLicense">
                  <el-input v-model="certForm.driverLicense" placeholder="请输入驾驶证号码"></el-input>
                </el-form-item>
                <el-form-item label="驾驶证类型" prop="driverLicenseType">
                  <el-select v-model="certForm.driverLicenseType" placeholder="请选择驾驶证类型" style="width: 100%">
                    <el-option label="A1" value="A1"></el-option>
                    <el-option label="A2" value="A2"></el-option>
                    <el-option label="B1" value="B1"></el-option>
                    <el-option label="B2" value="B2"></el-option>
                    <el-option label="C1" value="C1"></el-option>
                    <el-option label="C2" value="C2"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="驾驶证有效期" prop="driverLicenseExpiry">
                  <el-date-picker type="date" placeholder="选择日期" v-model="certForm.driverLicenseExpiry" style="width: 100%"></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateCertInfo" :loading="certLoading">保存证件信息</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <el-tab-pane label="密码修改" name="password">
              <el-form :model="pwdForm" :rules="pwdRules" ref="pwdForm" label-width="100px">
                <el-form-item label="原密码" prop="oldPassword">
                  <el-input type="password" v-model="pwdForm.oldPassword" placeholder="请输入原密码" show-password></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input type="password" v-model="pwdForm.newPassword" placeholder="请输入新密码" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input type="password" v-model="pwdForm.confirmPassword" placeholder="请再次输入新密码" show-password></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updatePassword" :loading="pwdLoading">修改密码</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { updateUserInfo, updatePassword } from '@/api/user'

export default {
  name: 'UserProfile',
  computed: {
    ...mapState({
      storeUserInfo: state => state.user.userInfo || {}
    })
  },
  data() {
    // 密码验证
    const validatePass = (rule, value, callback) => {
      if (value !== this.pwdForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    
    return {
      activeTab: 'basic',
      loading: false,
      certLoading: false,
      pwdLoading: false,
      userInfo: {
        id: '',
        username: '',
        createTime: '',
        orderCount: 0,
        favoriteCount: 0
      },
      userForm: {
        username: '',
        phone: '',
        email: '',
        realName: '',
        gender: 1,
        birthday: ''
      },
      userRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ]
      },
      certForm: {
        idCard: '',
        driverLicense: '',
        driverLicenseType: '',
        driverLicenseExpiry: ''
      },
      certRules: {
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
        ],
        driverLicense: [
          { required: true, message: '请输入驾驶证号', trigger: 'blur' }
        ],
        driverLicenseType: [
          { required: true, message: '请选择驾驶证类型', trigger: 'change' }
        ],
        driverLicenseExpiry: [
          { required: true, message: '请选择驾驶证有效期', trigger: 'change' }
        ]
      },
      pwdForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      pwdRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadUserInfo()
  },
  methods: {
    // 加载用户信息
    loadUserInfo() {
      // 如果store中没有用户信息，则获取
      if (!this.storeUserInfo || !this.storeUserInfo.name) {
        this.$store.dispatch('user/getInfo').then(() => {
          this.initUserData()
        })
      } else {
        this.initUserData()
      }
    },
    
    // 初始化用户数据
    initUserData() {
      const userInfo = this.storeUserInfo
      
      // 更新用户基本信息
      this.userInfo = {
        id: userInfo.id || '',
        username: userInfo.name || '',
        createTime: userInfo.createTime ? this.formatDate(userInfo.createTime) : '',
        orderCount: userInfo.orderCount || 0,
        favoriteCount: userInfo.favoriteCount || 0
      }
      
      // 更新用户表单
      this.userForm = {
        username: userInfo.name || '',
        phone: userInfo.phone || '',
        email: userInfo.email || '',
        realName: userInfo.realName || '',
        gender: userInfo.gender || 1,
        birthday: userInfo.birthday || ''
      }
      
      // 更新证件信息
      this.certForm = {
        idCard: userInfo.idCard || '',
        driverLicense: userInfo.driverLicense || '',
        driverLicenseType: userInfo.driverLicenseType || '',
        driverLicenseExpiry: userInfo.driverLicenseExpiry || ''
      }
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    
    // 更新用户信息
    updateUserInfo() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.loading = true
          
          // 构造符合后端CustomerDTO格式的数据
          const updateData = {
            name: this.userForm.username,
            phone: this.userForm.phone,
            email: this.userForm.email,
            realName: this.userForm.realName,
            gender: this.userForm.gender,
            birthday: this.userForm.birthday,
            idNumber: this.certForm.idCard,
            address: this.userForm.address || ''
          }
          
          updateUserInfo(updateData)
            .then(() => {
              this.$message.success('个人信息更新成功')
              // 更新Vuex中的用户信息
              this.$store.dispatch('user/getInfo')
            })
            .catch(error => {
              this.$message.error(error.message || '更新失败，请稍后重试')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    
    // 更新证件信息
    updateCertInfo() {
      this.$refs.certForm.validate(valid => {
        if (valid) {
          this.certLoading = true
          
          // 这里应该调用更新证件信息的API
          setTimeout(() => {
            this.$message.success('证件信息更新成功')
            this.certLoading = false
          }, 1000)
        }
      })
    },
    
    // 更新密码
    updatePassword() {
      this.$refs.pwdForm.validate(valid => {
        if (valid) {
          this.pwdLoading = true
          
          updatePassword({
            oldPassword: this.pwdForm.oldPassword,
            newPassword: this.pwdForm.newPassword
          })
            .then(() => {
              this.$message.success('密码修改成功，请重新登录')
              this.$store.dispatch('user/logout').then(() => {
                this.$router.push('/login')
              })
            })
            .catch(error => {
              this.$message.error(error.message || '密码修改失败，请稍后重试')
            })
            .finally(() => {
              this.pwdLoading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px 0;
  
  .page-title {
    margin-bottom: 20px;
    
    h2 {
      font-size: 24px;
      font-weight: 500;
      color: #303133;
      margin: 0;
    }
  }
  
  .card {
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
    margin-bottom: 20px;
  }
  
  .user-card {
    text-align: center;
    
    .user-avatar {
      margin-bottom: 20px;
      
      .el-avatar {
        margin-bottom: 10px;
      }
      
      .change-avatar {
        display: block;
        margin: 0 auto;
      }
    }
    
    .user-info {
      margin-bottom: 20px;
      
      .user-name {
        font-size: 18px;
        margin: 0 0 10px 0;
      }
      
      .user-id, .user-since {
        color: #909399;
        margin: 5px 0;
      }
    }
    
    .user-stats {
      display: flex;
      justify-content: space-around;
      border-top: 1px solid #ebeef5;
      padding-top: 20px;
      
      .stat-item {
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #409EFF;
        }
        
        .stat-label {
          color: #606266;
          font-size: 12px;
        }
      }
    }
  }
  
  .info-card {
    min-height: 500px;
  }
}

@media (max-width: 768px) {
  .profile-container {
    .user-card {
      margin-bottom: 20px;
    }
  }
}
</style> 